﻿using System;
using System.IO;
using System.Xml.Serialization;
using TasksDataXml.Helpers;

namespace TasksDataXml.Data
{
    [XmlRoot("TaskData")]
    public class Task : BaseDataItem
    {
        [XmlAttribute("Id")]
        public string Id
        {
            get { return GuidId.ToString(); }
            set
            {
                Guid g;
                if (Guid.TryParse(value, out g))
                {
                    GuidId = g;
                }
            }
        }

        [XmlElement("Description")]
        public string Desc { get; set; }
        
        [XmlElement("Note")]
        public string Note { get; set; }

        [XmlElement("IssueDate")]
        public string IssueDateString
        {
            get { return IssueDate.ToiBwaveMobileString(); }
            set
            {
                Exception ex;
                var date = value.ToiBwaveMobileDate(out ex);
                if (ex == null)
                    IssueDate = date;
            }
        }

        [XmlIgnore]
        public Guid GuidId { get; set; }

        [XmlIgnore]
        public DateTime IssueDate { get; set; }

        [XmlElement("IsCompleted")]
        public bool IsCompleted;

        [XmlIgnore]
        public override string Folder
        {
            get { return "Tasks"; }
        }

        public override void AttachCallbacks(IBaseDataItem parentCategory)
        {
            
        }

        [XmlIgnore]
        public override string Filename
        {
            get { return GuidId+"task.xml"; }
        }

        internal void MoveTask(Category target)
        {
            if (target != null)
            {
                if (NotifyParentMove != null)
                    NotifyParentMove(this);

                target.AddTask(this);
            }
        }

        public override void Dispose()
        {
            DeleteTaskFile();
        }

        private void DeleteTaskFile()
        {
            var path = PathUtility.GetCategoriesPath(null);
            File.Delete(GetFullPath(path));
        }
    }
}
